<template>
    <div class="async_task_container">
        <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :row-key="getRowKey"
            :fetch-params="state.searchParams"
            :fetch-data-format="fetchDataFormat"
            :fetch-api="getAsyncList"
            @sortChange="handleSortChange">
            <template #headerOperate>
                <el-button :icon="Refresh" @click="reloadTable">刷新进度</el-button>
            </template>
        </ZwTable>
    </div>
    <!-- 详情抽屉 -->
    <DetailDrawer :id="id" v-model="showDrawer" />
    <ZWDeletdialog ref="DeletdialogRef" @submit="onSubmit" />
</template>

<script setup lang="tsx">
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import { ElMessage } from 'element-plus';
import { Refresh } from '@element-plus/icons-vue';
import { ref, reactive, computed, nextTick } from 'vue';
import { deepCopy } from '@/utils/helper';
import DetailDrawer from './components/DetailDrawer.vue';
import searchFormOption, { subOptionList } from './configuration/searchOption';
import { tableColumnOption, RowOption } from './configuration/tableOption';
import { getAsyncList, doAsyncDownload, doCancelAsync, getAsyncFileIsLost } from '@/api/channelconfig/asyncTask';
import { downloadFile } from '@/utils/utils';
import { DOWLOAD_FILE } from '@/utils/smartMarketing.js';

/* =======================搜索表格======================== */

const defaultParams = {
    title: '', //标题
    async_no: '',
    created_ids: [],
    task_state: 0, //任务状态 1-未开始 2-进行中 3-已完成（执行成功） 4-异常（执行失败）5-已取消 6-已失效
    begin_time: [],
    finish_time: [],
    type: 0, //任务类型 1-导入任务 2-导出任务 3-数据转移
    module_type: 0
};

let sort: any = {
    id: 'desc'
};

// 表格
const tableRef = ref<HTMLElement | any>(null);
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = computed(() => {
    return searchFormOption;
});
const search = (v: any) => {
    tableRef.value.getTable().clearSelection();
    state.searchParams = { ...deepCopy(defaultParams), ...v, sort };
};
const reset = (v: any) => {
    tableRef.value.getTable().clearSelection();
    tableRef.value.getTable().clearSort();
    state.searchParams = { ...deepCopy(defaultParams) };
    subOptionList.splice(0);
};

const getRowKey = (row: any) => {
    return row.id;
};
/**
 * @description: 列表映射 添加主任务子任务折叠功能
 * @param {*} list
 * @return {*}
 */
const fetchDataFormat = (list: any) => {
    return list.map((item: any) => {
        // 判断条件  task_type  1-单级任务 2-多级任务      sub_tasks  子任务列表
        if (item.task_type === 2 && item.sub_tasks && item.sub_tasks.length) {
            item.children = item.sub_tasks;
        }
        return item;
    });
};

const tableOption = tableColumnOption({
    detail: (row: RowOption) => showDetail(row), // 详情
    download: (row: RowOption) => handleDownloadFile(row), // 下载文件
    cancel: (row: RowOption) => doCancel(row) // 取消
});

// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};

const descMap = {
    ascending: 'asc',
    descending: 'desc'
};
const handleSortChange = ({ order, prop }: any) => {
    sort = { [prop]: descMap[order] };
    state.searchParams.sort = sort;
    // reloadTable()
};
/* =======================搜索表格======================== */

/* ============================操作-start============================ */
let params = {};
// 查看详情
const showDetail = (row: RowOption) => {
    id.value = row.id;
    showDrawer.value = true;
};
// 下载
const handleDownloadFile = async (row: RowOption) => {
    params = { id: row.id };
    if (row.task_state === 6) return ElMessage.warning('已超过文件30天有效期“');
    // 是否超过30天
    const { is_thirty } = (await getAsyncFileIsLost(params)) || {};
    // 已失效
    if (is_thirty) {
        row.task_state = 6;
        row.task_state_name = '已失效';
        return ElMessage.warning('已超过文件30天有效期“');
    }
    // 未失效进行下载
    const { url } = (await doAsyncDownload(params)) || {};
    // url ? downloadFile(url, '_blank') : ElMessage.warning('暂无文件url');
    url ? DOWLOAD_FILE(url, decodeURI(getFilenameFromUrl(url))) : ElMessage.warning('暂无文件url');
};
/**
 * 通过url获取文件名称，
 * 为了解决doAsyncDownload接口后端返回的name字段无后缀名
 * 导致的文件无法打开的问题
 * @param url 文件url地址
 */
const getFilenameFromUrl = (url: string): string => {
    const pathname = new URL(url).pathname;
    const index = pathname.lastIndexOf('/');
    return -1 !== index ? pathname.substring(index + 1) : pathname;
};
// 取消
const DeletdialogRef = ref();
const doCancel = async (row: RowOption) => {
    params = { id: row.id };
    DeletdialogRef.value.appDialog.title = '取消确认';
    DeletdialogRef.value.content = '确认要取消该异步任务吗？';
    DeletdialogRef.value.appDialog.visible = true;
};
const onSubmit = async () => {
    await doCancelAsync(params);
    reloadTable();
};
/* ============================操作-end============================ */

/* =======================详情抽屉======================== */
const id = ref();
const showDrawer = ref(false);
/* =======================详情抽屉======================== */
</script>

<style lang="scss" scoped>
.async_task_container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

.dropdown_btn {
    margin-right: 10px;
}

:deep(.status_point) {
    --status-bgcolor: #ffd500;

    &::before {
        content: '';
        display: inline-block;
        width: 8px;
        height: 8px;
        margin-right: 8px;
        background-color: var(--status-bgcolor);
        border-radius: 4px;
    }
}

:deep(.total_num),
:deep(.sussess_num),
:deep(.fail_num) {
    font-size: 12px;
    font-family: PingFangSC-Regular, 'PingFang SC';
    margin-left: 4px;
    color: #33302d;
}

:deep(.sussess_num) {
    color: #32d1ad;
}

:deep(.fail_num) {
    color: #f14144;
}

:deep(.el-progress.is-warning .el-progress__text) {
    color: #f14144;
}

:deep(.el-table__row .el-table__cell:first-of-type .cell) {
    // &  {
    // }
    display: flex;
    align-items: center;
}
</style>
